import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs/Rx';
import { MatDialog } from '@angular/material';
import { RestService } from '../services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { PersonDetailsComponent } from './person-details/person-details.component';
import { environment } from 'environments/environment';

import * as _ from 'lodash';

@Component({
  templateUrl: './mcenter.component.html',
  styleUrls: ['./mcenter.component.css'],
})
export class McenterComponent implements OnInit, OnDestroy {
  routeSubscription: Subscription;

  refreshInterval = environment.interval;
  refreshTask: any;

  displayedColumns: string[] = ['number', 'personName', 'building', 'level', 'room', 'bed', 'device1Id','device2Id', 'nurseName', 'state', 'actions'];
  displayedColumnsDevice: string[] = ['number', 'deviceId', 'personName', 'updateTime'];
  institution: any;

  personTotal: any = '-';
  personAbnormal: any = '-';
  personNormal: any = '-';
  personAway: any = '-';

  deviceTotal: any = '-';
  deviceInUse: any = '-';
  deviceToUse: any = '-';
  deviceAbnormal: any = '-';

  abnormalPersonClass = 'inactive';
  normalPersonClass = 'inactive';
  allPersonClass = 'inactive';
  awayPersonClass = 'inactive';

  allDeviceClass = 'inactive';
  inUseDeviceClass = 'inactive';
  toUseDeviceClass = 'inactive';
  abnormalDeviceClass = 'inactive';

  showLoadingFlag = false;

  showAbnormalPerson = false;
  showNormalPerson = false;
  showAllPerson = false;
  showAwayPerson = false;

  showAllDevice = false;
  showInUseDevice = false;
  showToUseDevice = false;
  showAbnormalDevice = false;

  dataSource = [];

  showPersonDetails = false;
  person: any;
  showPersonBandDetails = false;

  constructor(public dialog: MatDialog,
              private router: Router,
              private route: ActivatedRoute,
              private translate: TranslateService,
              private rest: RestService) {
    this.institution = this.rest.getInstitution();
    this.person = {};
  }

  getBgClass() {
    return (this.showPersons() || this.showDevices() || this.showPersonDetails) ? 'hst-bg-blank' : 'hst-bg';
  }
  getBandClass() {
    return (this.showPersons() || this.showDevices() || this.showPersonBandDetails) ? 'hst-bg-blank' : 'hst-bg';
  }

  getListClass() {
    return this.showPersonDetails ? 'wdl-container-person' : 'wdl-container';
  }

  resetStaticsClass() {
    this.abnormalPersonClass = 'inactive';
    this.normalPersonClass = 'inactive';
    this.allPersonClass = 'inactive';
    this.awayPersonClass = 'inactive';
    this.allDeviceClass = 'inactive';
    this.inUseDeviceClass = 'inactive';
    this.toUseDeviceClass = 'inactive';
    this.abnormalDeviceClass = 'inactive';
  }

  navigateTo(item) {
    this.router.navigateByUrl('/mcenter/' + item);
  }

  reset() {
    this.dataSource = [];

    this.showPersonDetails = false;

    this.showPersonBandDetails = false;

    this.showAbnormalPerson = false;
    this.showNormalPerson = false;
    this.showAllPerson = false;
    this.showAwayPerson = false;

    this.showAllDevice = false;
    this.showInUseDevice = false;
    this.showToUseDevice = false;
    this.showAbnormalDevice = false;
  }

  switchTable(table) {
    switch (table) {
    case 'allPerson':
      this.resetStaticsClass();
      if (this.showAllPerson) {
        this.showAllPerson = false;
        this.showPersonDetails = false;
        return;
      }

      this.reset();
      this.showAllPerson = true;
      this.allPersonClass = 'active';
      break;
    case 'normalPerson':
      this.resetStaticsClass();
      if (this.showNormalPerson) {
        this.showNormalPerson = false;
        this.showPersonDetails = false;
        return;
      }

      this.reset();
      this.showNormalPerson = true;
      this.normalPersonClass = 'active';
      break;
    case 'abnormalPerson':
      this.resetStaticsClass();
      if (this.showAbnormalPerson) {
        this.showAbnormalPerson = false;
        this.showPersonDetails = false;
        return;
      }

      this.reset();
      this.showAbnormalPerson = true;
      this.abnormalPersonClass = 'active';
      break;
    case 'awayPerson':
      this.resetStaticsClass();
      if (this.showAwayPerson) {
        this.showAwayPerson = false;
        this.showPersonDetails = false;
        return;
      }

      this.reset();
      this.awayPersonClass = 'active';
      this.showAwayPerson = true;
      break;
    case 'allDevice':
      this.resetStaticsClass();
      if (this.showAllDevice) {
        this.showAllDevice = false;
        return;
      }

      this.reset();
      this.showAllDevice = true;
      this.allDeviceClass = 'active';
      break;
    case 'inUseDevice':
      this.resetStaticsClass();
      if (this.showInUseDevice) {
        this.showInUseDevice = false;
        return;
      }

      this.reset();
      this.showInUseDevice = true;
      this.inUseDeviceClass = 'active';
      break;
    case 'toUseDevice':
      this.resetStaticsClass();
      if (this.showToUseDevice) {
        this.showToUseDevice = false;
        return;
      }

      this.reset();
      this.showToUseDevice = true;
      this.toUseDeviceClass = 'active';
      break;
    case 'abnormalDevice':
      this.resetStaticsClass();
      if (this.showAbnormalDevice) {
        this.showAbnormalDevice = false;
        return;
      }

      this.reset();
      this.showAbnormalDevice = true;
      this.abnormalDeviceClass = 'active';
      break;
    }

    this.fetchTableData();
  }

  showPersons() {
    return this.showAllPerson || this.showNormalPerson || this.showAbnormalPerson || this.showAwayPerson;
  }

  showDevices() {
    return this.showAllDevice || this.showAbnormalDevice || this.showInUseDevice || this.showToUseDevice;
  }

  hidePerson() {
    this.showPersonDetails = false;
  }
  hidePersonBand(){
    this.showPersonBandDetails = false;
  }
  openMonitor(row) {
    this.person = row;
    this.showPersonDetails = true;
  }

  openBandMonitor(row){
    if(row.device2Id!=null) {
      this.person = row;
      this.showPersonBandDetails = true;
    }
  }
  openHist(row) {
    this.dialog.open(PersonDetailsComponent, {
      disableClose: true,
      autoFocus: false,
      width: '1200px',
      data: {
        person: row
      }
    });
  }

  getAlarmText(person) {
    const alarms = [];

    if (person.deviceAlarmFlag) {
      alarms.push(this.translate.get('DEVICE')['value']);
    }

    if (person.awayAlarmFlag) {
      alarms.push(this.translate.get('AWAY')['value']);
    }

    if (person.wetAlarmFlag) {
      alarms.push(this.translate.get('WET')['value']);
    }

    if (person.sideAlarmFlag) {
      alarms.push(this.translate.get('SIDE')['value']);
    }

    if (person.upAlarmFlag) {
      alarms.push(this.translate.get('UP')['value']);
    }

    if (person.heartAlarmFlag) {
      alarms.push(this.translate.get('HEART')['value']);
    }

    if (person.breatheAlarmFlag) {
      alarms.push(this.translate.get('BREATHE')['value']);
    }

    if (person.moveAlarmFlag) {
      alarms.push(this.translate.get('MOVE')['value']);
    }

    if (person.ringAlarmFlag) {
      alarms.push(this.translate.get('RING')['value']);
    }

    if (person.turnOverReminderAlarmFlag) {
      alarms.push(this.translate.get('TURN_OVER')['value']);
    }

    if (person.leftAlarmFlag) {
      alarms.push(this.translate.get('LEFT')['value']);
    }

    if (person.rightAlarmFlag) {
      alarms.push(this.translate.get('RIGHT')['value']);
    }

    if (alarms.length < 1) {
      return this.translate.get('normal')['value'];
    } else {
      return alarms.join(', ');
    }
  }

  convertData(items) {
    items.forEach(item => {
      if (item.bedString && item.bedString.indexOf('##') > -1) {
        const bedStrings = item.bedString.split('##');
        if (bedStrings.length > 0) {
          item['building'] = bedStrings[0];
        } else {
          item['building'] = '-';
        }

        if (bedStrings.length > 1) {
          item['level'] = bedStrings[1];
        } else {
          item['level'] = '-';
        }

        if (bedStrings.length > 2) {
          item['room'] = bedStrings[2];
        } else {
          item['room'] = '-';
        }

        if (bedStrings.length > 3) {
          item['bed'] = bedStrings[3];
        } else {
          item['bed'] = '-';
        }
      } else {
        item['building'] = '-';
        item['level'] = '-';
        item['room'] = '-';
        item['bed'] = '-';
      }
    });

    return items;
  }

  getAbnormalDeviceTime() {
    // Not updated for more than 1 minutes
    return new Date().getTime() - 1 * 60 * 1000;
  }

  fetchTableData() {
    let url;
    if (this.showAllPerson) {
      url = 'data/person/search/findallin';
    } else if (this.showNormalPerson) {
      url = 'data/person/search/findnormalin';
    } else if (this.showAbnormalPerson) {
      url = 'data/person/search/findabnormalin';
    } else if (this.showAwayPerson) {
      url = 'data/person/search/findawayin';
    } else if (this.showAllDevice) {
      url = 'data/device/search/findall';
    } else if (this.showAbnormalDevice) {
      url = 'data/device/search/findabnormal';
    } else if (this.showInUseDevice) {
      url = 'data/device/search/findinuse';
    } else if (this.showToUseDevice) {
      url = 'data/device/search/findtouse';
    }

    if (url) {
      this.showLoadingFlag = true;
      const parameters = {
        institutionId: this.institution.id
      };

      if (this.showAbnormalDevice) {
        parameters['updateTime'] = this.getAbnormalDeviceTime();
      }

      this.rest.getWithParams(url, parameters).subscribe(data => {
        this.processTableData(data['_embedded']);
        this.showLoadingFlag = false;
      }, () => {
        this.dataSource = [];
        this.showLoadingFlag = false;
      });
    } else {
      this.dataSource = [];
    }
  }

  processTableData(data) {
    if (this.showAllPerson || this.showNormalPerson || this.showAbnormalPerson || this.showAwayPerson) {
      this.dataSource = this.convertData(data['persons']);
    } else if (this.showAllDevice || this.showAbnormalDevice || this.showInUseDevice || this.showToUseDevice) {
      this.dataSource = data['devices'];
    }

    let itemNumber = 1;
    this.dataSource.forEach(item => {
      item['number'] = itemNumber++;
    });
  }

  refresh() {
    if (this.rest.getCurrentApp() !== 'mcenter') {
      return;
    }

    if (this.institution.id == 0) {
      this.institution = this.rest.getInstitution();
    }

    this.rest.getWithParams('api/pro/statistics', {institutionId: this.institution.id}).subscribe(resp => {
      this.personTotal = resp['countallin'];
      this.personNormal = resp['countnormalin'];
      this.personAway = resp['countawayin'];

      this.deviceTotal = resp['countall'];
      this.deviceInUse = resp['countinuse'];
      this.deviceAbnormal = resp['countabnormal'];

      this.personAbnormal = this.personTotal - this.personNormal;
      this.deviceToUse = this.deviceTotal - this.deviceInUse;
      this.scheduleNext();
    }, message => {
      console.error('Failed to retrieve data from server.');
      this.scheduleNext();
    });
  }

  scheduleNext() {
    if (this.rest.getCurrentApp() !== 'mcenter') {
      return;
    }

    this.refreshTask = setTimeout(() => {
      if (this.rest.getCurrentApp() !== 'mcenter') {
        return;
      }

      this.refresh();
    }, this.refreshInterval);
  }

  ngOnInit() {
    this.routeSubscription = this.route.params.subscribe(params => {
      const personId = params['person'];
      if (personId) {
        this.rest.getWithParams('/data/person/search/index', {index: personId}).subscribe(resp => {
          this.person = resp;
          this.showPersonDetails = true;
        });
      }

      this.refresh();
    });
  }

  ngOnDestroy() {
    if (this.refreshTask) {
      clearTimeout(this.refreshTask);
    }
  }
}
